package com.kai.service.impl;

import com.kai.JwtUtil.JwtUtil;
import com.kai.constant.UserConstant;
import com.kai.dto.RegisterDTO;
import com.kai.entity.User;
import com.kai.exception.AccountLockedException;
import com.kai.exception.AccountNotFoundException;
import com.kai.exception.IdCardExistException;
import com.kai.exception.PasswordErrorException;
import com.kai.mapper.UserMapper;
import com.kai.properties.JwtTokenProperties;
import com.kai.result.Result;
import com.kai.service.UserService;
import com.kai.vo.LoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    //JWT配置项
    @Autowired
    private JwtTokenProperties jwtTokenProperties;

    @Override
    public void register(RegisterDTO registerDTO) {
        //判断 用户名是否存在
        Integer count = userMapper.userNameIsExist(registerDTO.getUserName());
        if (count != 0) {
            throw new AccountNotFoundException(UserConstant.ACCOUNT_NOT_FOUND);
        }
        //判断 邮箱是否存在
        count = userMapper.emailIsExist(registerDTO.getEmail());
        if (count != 0) {
            throw new AccountNotFoundException(UserConstant.ACCOUNT_NOT_FOUND);
        }
        // 使用MD5对密码进行加密
        String password = DigestUtils.md5DigestAsHex(registerDTO.getPassword().getBytes());

        //注册
        User user = User.builder()
                .nickName(registerDTO.getNickName())
                .userName(registerDTO.getUserName())
                .password(password)
                .email(registerDTO.getEmail()).build();
        userMapper.insert(user);

    }

    @Override
    public void update(User user) {
        //判断身份证是否存在
        Integer count = userMapper.idCardIsExist(user.getIdCard());
        if (count != 0) {
            throw new IdCardExistException(UserConstant.ID_CARD_EXIST);
        }
        userMapper.update(user);
    }

    @Override
    public LoginVO login(String userName, String password) {

        //判断账号是否存在
        User user = userMapper.getUserByUserName(userName);
        if (user == null) {
            throw new AccountNotFoundException(UserConstant.ACCOUNT_NOT_FOUND);
        }
        //判断账户状态
        if (user.getStatus() == 5) {
            throw new AccountLockedException(UserConstant.ACCOUNT_LOCKED);
        }

        //查看评分如果评分小于3 设置为禁止接单
        if (user.getRating().compareTo(BigDecimal.valueOf(3)) < 0) {
            // 示例逻辑：设置用户为禁止接单状态
            LocalDateTime now = LocalDateTime.now();
            userMapper.setStatus(4, user.getId(), now);
        }

        //判断密码是否正确
        //用md5 加密密码 再和查询的密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!user.getPassword().equals(password)) {
            throw new PasswordErrorException(UserConstant.PASSWORD_ERROR);
        }

        //下发token
        Map<String, Object> claims = new HashMap<>();
        claims.put(UserConstant.USER_ID, user.getId());
        String token = JwtUtil.createJWT
                (jwtTokenProperties.getSecretKey(), jwtTokenProperties.getTtlMillis(), claims);

        return LoginVO.builder().token(token)
                .id(user.getId())
                .name(user.getName())
                .nickName(user.getNickName())
                .avatar(user.getAvatar())
                .build();


    }

}
